// @ts-check
const { out, Route } = require('f2e-serve')
const { IncomingMessage, ServerResponse } = require('http')

const state = {
    src: 'http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4',
    currentTime: 0,
    playing: false,
}
/**
 * @type {Set<ServerResponse<IncomingMessage>>}
 */
const responses = new Set()

/**
 * @type {import('f2e-serve').Callback} 
 */
const getTime = (req, resp) => {
    if (req && resp) {
        responses.add(resp)
        req.addListener('close', function () {
            responses.delete(resp)
        })
        resp.write(`data:${JSON.stringify(state)}\n\n`)
    }
}
/**
 * @type {import('f2e-serve').Callback} 
 */
const setTime = (req) => {
    const { time, playing } = req?.data || {}
    const currentTime = Number(time)
    const _playing = ({ 'true': true, 'false': false })[playing]
    if (typeof _playing === 'boolean') {
        state.playing = _playing
    }
    if (!isNaN(currentTime)) {
        state.currentTime = currentTime
    }
    responses.forEach(resp => {
        resp.write(`data:${JSON.stringify(state)}\n\n`)
    })
    return {
        success: true,
        state,
    }
}

/**
 * @type {import('f2e-serve').Callback} 
 */
const changeSrc = req => {
    const { src } = req?.body || {}
    if (src) {
        state.src = src
        state.currentTime = 0
        state.playing = false
    }
    responses.forEach(resp => {
        resp.write(`data:${JSON.stringify(state)}\n\n`)
    })
    return {
        success: true,
        state,
    }
}
/**
 * @type {import('f2e-server').MiddlewareCreater} 
 */
const middle = function (conf) {
    const route = new Route()
    route.on('sse/currentTime', out.ServerSent(getTime, conf))
    route.on('api/currentTime', out.JsonOut(setTime, conf))
    route.on('api/changeSrc', out.JsonOut(changeSrc, conf))
    return {
        onRoute: route.execute
    }
}

module.exports = middle